﻿///***************************************************************
/// 시  스  템 : Updms.Com
/// 단위시스템 : COM
/// 계      층 : Presentation Layer
/// 프로그램명 : Com1020m
/// 파  일  명 : Com1020m.aspx.cs
/// 설      명 : 메뉴정렬관리
///***************************************************************
/// 수정ID 일자       이름     내용
///---------------------------------------------------------------
/// CH001  2012-09-11 송시명   최초 작성
///***************************************************************
using System;
using System.Data;
using System.Text;
using System.Web.UI;
using System.Web.UI.WebControls;

using SMFramework.Data;
using SMFramework.Utility;

using Base.AppFramework.Web.UI.CommandBar;
using Base.Dac;
using Updms.Com.Exe;


namespace Updms.Com
{
	public partial class Com1020m : Updms.Common.BaseClass.PageBase
	{
		#region 전역영역

		//프로그램상수
		public static readonly string PID = "Com1020m";
		public static readonly string gs_path_info = "/updms/Com/" + PID + ".aspx";

		Global global = new Global();
		CommCode.Com com = new CommCode.Com(LANG_SET);

		//검색
		protected string kw1 = "";	// user_id
		protected string kw2 = "";	// access_level

		//메뉴 선택값
		protected string gs_sm = "";

		//페이지모드
		private string gs_page_mode = "";

		#endregion

		#region Page_Load, OnPageLoad

		protected void Page_Load(object sender, EventArgs e)
		{
			SetInit();
			if (!Page.IsPostBack)
			{
				// 최초 화면 로딩시 처리해야 할 부분
				OnPageLoad();
			}
			else
			{
				setScrollLocation();
			}
		}

		// OnPageLoad
		private void OnPageLoad()
		{
			SetLiterals(global.GetLabelInfoByPgmId(PID, LANG_SET));
			SetLayout();
			SetSearchParameter();
			SearchProcess();
		}

		#endregion

		#region InitializeComponent

		private void InitializeComponent()
		{
			this.Load += new System.EventHandler(this.Page_Load);
			this.PreRender += new System.EventHandler(this.Page_PreRender);
		}

		#endregion

		#region SetClientScript

		//스크롤바 위치 고정
		protected void setScrollLocation()
		{
			ClientScriptManager cs = this.ClientScript;
			cs.RegisterStartupScript(this.GetType(), "setScroll", get_SetScrollLocation());
		}

		//스크롤바 위치
		public static string get_SetScrollLocation()
		{
			StringBuilder sb = new StringBuilder();

			sb.Append("<script language=javascript>");
			sb.Append("scrollTo();");
			sb.Append("</script>");

			return sb.ToString();
		}

		#endregion

		#region SetInit, SetSearchParameter, ShowKeywordLabel

		//초기값설정
		private void SetInit()
		{
			lbl_search_flag.Text = "INIT";

			gs_sm = (Request.QueryString["sm"] == null || Request.QueryString["sm"].Trim().Length != 7)
					? global.GetDirDepth(PID) : Request.QueryString["sm"].ToString();

			gs_page_mode = (Request.QueryString["page_mode"] == null || Request.QueryString["page_mode"].Trim().Length == 0)
					? "" : Request.QueryString["page_mode"].ToString();
		}

		//검색파라미터
		private void SetSearchParameter()
		{
			switch (lbl_search_flag.Text.Trim().ToUpper())
			{
				case "INIT":
					if (String.IsNullOrEmpty(Request.QueryString["kw1"]))	// url에 값이 없으면
					{
						kw1 = USER_ID;
					}
					else
					{
						kw1 = Server.UrlDecode(Request.QueryString["kw1"]);
					}
					if (String.IsNullOrEmpty(Request.QueryString["kw2"]))	// url에 값이 없으면
					{
						kw2 = ACCESS_LEVEL;
					}
					else
					{
						kw2 = Server.UrlDecode(Request.QueryString["kw2"]);
					}
					break;
				case "SEARCH":
					kw1 = USER_ID;
					kw2 = ACCESS_LEVEL;
					break;
			}
		}

		#endregion

		#region 마스터 (SetLayout)

		//레이아웃
		private void SetLayout()
		{
			com.SetMenuDiv(rbl_menu_div);
		}

		#endregion

		#region 디테일 Method (상위메뉴, 하위메뉴)

		#region 상위메뉴

		//라벨 위로
		private void UpHighPgm()
		{
			if (lbox_high_pgm_list.SelectedIndex > -1)
			{
				int li_pre_idx = lbox_high_pgm_list.SelectedIndex;
				if (li_pre_idx > 0)
				{
					lbox_high_pgm_list.Items.Insert(li_pre_idx - 1, lbox_high_pgm_list.Items[li_pre_idx]);
					lbox_high_pgm_list.Items.RemoveAt(li_pre_idx + 1);
					lbox_high_pgm_list.SelectedIndex = li_pre_idx - 1;
				}
			}

			ResetHighPgmIndex();
		}

		//라벨아래로
		private void DownHighPgm()
		{
			if (lbox_high_pgm_list.SelectedIndex > -1)
			{
				int li_pre_idx = lbox_high_pgm_list.SelectedIndex;
				if (li_pre_idx < lbox_high_pgm_list.Items.Count - 1)
				{
					li_pre_idx++;
					lbox_high_pgm_list.Items.Insert(li_pre_idx - 1, lbox_high_pgm_list.Items[li_pre_idx]);
					lbox_high_pgm_list.Items.RemoveAt(li_pre_idx + 1);
				}
			}

			ResetHighPgmIndex();
		}

		//라벨인덱스 재정렬
		private void ResetHighPgmIndex()
		{
			int num = lbox_high_pgm_list.Items.Count;
			num--;
			for (int i = num; i > -1; i--)
			{
				string ls_label_nm = lbox_high_pgm_list.Items[i].Text;
				string ls_prefix = ls_label_nm.Substring(0, 1);	//D01 TO-DO -> D

				int li_split_start = ls_label_nm.LastIndexOf("|");
				if (li_split_start > 0)
				{
					ls_label_nm = ls_label_nm.Substring(li_split_start, ls_label_nm.Length - li_split_start);
				}

				lbox_high_pgm_list.Items[i].Text = ls_prefix + (i + 1).ToString().PadLeft(2, '0') + ls_label_nm;
			}
		}

		#endregion

		#region 하위메뉴

		//라벨 위로
		private void UpPgm()
		{
			if (lbox_pgm_list.SelectedIndex > -1)
			{
				int li_pre_idx = lbox_pgm_list.SelectedIndex;
				if (li_pre_idx > 0)
				{
					lbox_pgm_list.Items.Insert(li_pre_idx - 1, lbox_pgm_list.Items[li_pre_idx]);
					lbox_pgm_list.Items.RemoveAt(li_pre_idx + 1);
					lbox_pgm_list.SelectedIndex = li_pre_idx - 1;
				}
			}

			ResetPgmIndex();
		}

		//라벨아래로
		private void DownPgm()
		{
			if (lbox_pgm_list.SelectedIndex > -1)
			{
				int li_pre_idx = lbox_pgm_list.SelectedIndex;
				if (li_pre_idx < lbox_pgm_list.Items.Count - 1)
				{
					li_pre_idx++;
					lbox_pgm_list.Items.Insert(li_pre_idx - 1, lbox_pgm_list.Items[li_pre_idx]);
					lbox_pgm_list.Items.RemoveAt(li_pre_idx + 1);
				}
			}

			ResetPgmIndex();
		}

		//라벨인덱스 재정렬
		private void ResetPgmIndex()
		{
			int num = lbox_pgm_list.Items.Count;
			num--;
			for (int i = num; i > -1; i--)
			{
				string ls_label_nm = lbox_pgm_list.Items[i].Text;
				string ls_prefix = ls_label_nm.Substring(0, 3);	//D010001 -> D01

				int li_split_start = ls_label_nm.LastIndexOf("[");
				if (li_split_start > 0)
				{
					ls_label_nm = ls_label_nm.Substring(li_split_start, ls_label_nm.Length - li_split_start);
				}

				lbox_pgm_list.Items[i].Text = ls_prefix + (i + 1).ToString().PadLeft(4, '0') + ls_label_nm;
			}

			for (int j = 0; j < lbox_pgm_list.Items.Count; j++)
			{
				string[] ls_texts = lbox_pgm_list.Items[j].Text.Split('['); //D010001[Com1010m] 공통코드관리 
				string[] ls_values = lbox_pgm_list.Items[j].Value.Split('|'); //120|D

				string ls_dir_depth = "";
				string ls_pgm_div = "";

				if (ls_texts.Length > 1)
				{
					ls_dir_depth = ls_texts[0]; //D010001
					ls_pgm_div = ls_values[1]; //D

					if (ls_pgm_div == "D")
					{
						string ls_d_prefix = ls_dir_depth.Substring(0, 3);	//D01

						//끝까지 돌면서 파일의 Dxx을 디렉토리의 Dxx로 변경
						for (int k = j; k < lbox_pgm_list.Items.Count; k++)
						{
							string ls_label_nm = lbox_pgm_list.Items[k].Text;
							ls_label_nm = ls_label_nm.Substring(3, ls_label_nm.Length - 3); //Dxx를 제외한 나머지 이름
							string[] ls_sub_values = lbox_pgm_list.Items[k].Value.Split('|'); //120|D
							
							if (ls_sub_values[1] == "F")
							{
								lbox_pgm_list.Items[k].Text = ls_d_prefix + ls_label_nm;
							}
						}
					}
				}
			}
		}

		#endregion

		#endregion

		#region CRUD (SelectHighMenuProcess, SelectMenuProcess, SetHighMenuViewOrder, SetMenuViewOrder, SearchProcess)

		//상위메뉴
		private void SelectHighMenuProcess()
		{
			DataSet lo_ds = new DataSet();
			DataPack lo_dp = new DataPack();

			lo_dp.AddProperty("ls_lang_set", typeof(string), LANG_SET);

			using (Com1020m_NT _Com1020m_NT = new Com1020m_NT())
			{
				lo_ds.Merge(_Com1020m_NT.GetAllMenuList(lo_dp));
			}

			if (DataSetUtil.CheckRowCount(lo_ds, "UPDMS_COM_PGM"))
			{
				lbox_high_pgm_list.Items.Clear();
				lbox_high_pgm_list.DataSource = lo_ds.Tables[0];
				lbox_high_pgm_list.DataMember = "UPDMS_COM_PGM";
				lbox_high_pgm_list.DataTextField = "Text";
				lbox_high_pgm_list.DataValueField = "Value";
				lbox_high_pgm_list.DataBind();
			}
		}

		//하위메뉴
		private void SelectMenuProcess()
		{
			DataSet lo_ds = new DataSet();
			DataPack lo_dp = new DataPack();

			lo_dp.AddProperty("ls_lang_set", typeof(string), LANG_SET);

			using (Com1020m_NT _Com1020m_NT = new Com1020m_NT())
			{
				lo_ds.Merge(_Com1020m_NT.GetAllMenuList(lo_dp));
			}

			if (DataSetUtil.CheckRowCount(lo_ds, "UPDMS_COM_PGM"))
			{	
				lbox_pgm_list.Items.Clear();
				lbox_pgm_list.DataSource = lo_ds.Tables[1];
				lbox_pgm_list.DataMember = "UPDMS_COM_PGM";
				lbox_pgm_list.DataTextField = "Text";
				lbox_pgm_list.DataValueField = "Value";
				lbox_pgm_list.DataBind();
			}
		}

		//상위메뉴수정
		private void SetHighMenuViewOrder()
		{
			using (Com1020m_RT _Com1020m_RT = new Com1020m_RT())
			{
				int li_return = _Com1020m_RT.SetHighMenuViewOrder(SetHighValue(), USER_ID);
				string ls_msg_id = (li_return > 0) ? "MSG_INF_007" : (li_return == 0) ? "MSG_INF_022" : "MSG_ERR_105";	//저장되었습니다:변경된 내용이 없습니다:저장할 수 없습니다
				CallMsgBoxInAjax(ls_msg_id);

				SearchProcess();
			}
		}

		//하위메뉴수정
		private void SetMenuViewOrder()
		{
			using (Com1020m_RT _Com1020m_RT = new Com1020m_RT())
			{
				int li_return = _Com1020m_RT.SetMenuViewOrder(SetValue(), USER_ID);
				string ls_msg_id = (li_return > 0) ? "MSG_INF_007" : (li_return == 0) ? "MSG_INF_022" : "MSG_ERR_105";	//저장되었습니다:변경된 내용이 없습니다:저장할 수 없습니다
				CallMsgBoxInAjax(ls_msg_id);

				SearchProcess();
			}
		}

		//검색
		private void SearchProcess()
		{
			lbl_search_flag.Text = "SEARCH";
			SetSearchParameter();

			switch (rbl_menu_div.SelectedValue)
			{
				case "AF001":	//상위메뉴
					table_high_pgm.Visible = true;
					table_pgm.Visible = false;
					SelectHighMenuProcess();
					break;
				case "AF002":	//하위메뉴
					table_high_pgm.Visible = false;
					table_pgm.Visible = true;
					SelectMenuProcess();
					break;
				default:
					table_high_pgm.Visible = true;
					table_pgm.Visible = false;
					SelectHighMenuProcess();
					break;
			}
		}

		#endregion

		#region SetValue

		#region 상위메뉴

		//SetHighValue
		private string SetHighValue()
		{
			string ls_result = "<UPDMS>";

			for (int i = 0; i < lbox_high_pgm_list.Items.Count; i++)
			{
				string[] ls_texts = lbox_high_pgm_list.Items[i].Text.Split('|'); //D01|공통관리
				string[] ls_values = lbox_high_pgm_list.Items[i].Value.Split('|'); //120|D00

				string ls_dir_depth = "";
				string ls_org_dir_depth = "";
				string ls_seq = "";

				if (ls_texts.Length > 1)
				{
					ls_dir_depth = ls_texts[0];
				}

				if (ls_values.Length > 1)
				{
					ls_seq = ls_values[0];
					ls_org_dir_depth = ls_values[1];
				}

				string xml_dir_depth = "<Dir_Depth>" + ls_dir_depth.Trim() + "</Dir_Depth>";
				string xml_org_dir_depth = "<Org_Dir_Depth>" + ls_org_dir_depth.Trim() + "</Org_Dir_Depth>";
				string xml_seq = "<Seq>" + ls_seq.Trim() + "</Seq>";

				ls_result +=
					"<UPDMS_COM_PGM>"
						+ xml_dir_depth
						+ xml_org_dir_depth
						+ xml_seq
					+ "</UPDMS_COM_PGM>";
			}
			ls_result = ls_result + "</UPDMS>";

			return ls_result;
		}

		#endregion

		#region 하위메뉴

		//SetValue
		private string SetValue()
		{
			string ls_result = "<UPDMS>";

			for (int i = 0; i < lbox_pgm_list.Items.Count; i++)
			{
				string[] ls_texts = lbox_pgm_list.Items[i].Text.Split('['); //D010001[Com1010m] 공통코드관리 
				string[] ls_values = lbox_pgm_list.Items[i].Value.Split('|');

				string ls_dir_depth = "";
				string ls_pgm_id = "";
				string ls_seq = "";

				if (ls_texts.Length > 1)
				{
					ls_dir_depth = ls_texts[0];
					ls_pgm_id = ls_texts[1].Substring(0, 8); //Com1010m] 공통코드관리 -> Com1010m
				}

				//Seq
				if (ls_values.Length > 1)
				{
				    ls_seq = ls_values[0];
				}

				string xml_pgm_id = "<Pgm_Id>" + ls_pgm_id.Trim() + "</Pgm_Id>";
				string xml_dir_depth = "<Dir_Depth>" + ls_dir_depth.Trim() + "</Dir_Depth>";
				string xml_seq = "<Seq>" + ls_seq + "</Seq>";

				ls_result +=
					"<UPDMS_COM_PGM>"
						+ xml_pgm_id
						+ xml_dir_depth
						+ xml_seq
					+ "</UPDMS_COM_PGM>";
			}
			ls_result = ls_result + "</UPDMS>";

			return ls_result;
		}

		#endregion

		#endregion

		#region Page_PreRender, ChangePageMode

		// Page_PreRender
		private void Page_PreRender(object sender, System.EventArgs e)
		{
			if (!Page.IsPostBack)
			{
				using (AccessCheck access = new AccessCheck())
				{
					//접근권한 체크
					if (!access.CheckPgmAccessGrant(PID, USER_ID, ACCESS_LOG_INFO))
					{
						Response.Redirect(URL_NO_AUTHORITY_REDIRECT_BASE);	//사용자의 권한은 요청하신 페이지를 볼 수 없습니다
					}
					//사용권한별 버튼처리
					PagePreRender.SetVisibleCtrl(this, access.CheckPgmUsingGrant(USER_DIV, PID), access.GetVisibleCtrl(PID));
				}
			}
			ChangePageMode();
		}

		//ChangePageMode
		private void ChangePageMode()
		{
			switch (gs_page_mode)
			{
				case "":		//처음 페이지로드시
					Top.Visible = true;
					menu_area.Attributes.Add("class", "");
					ibtn_close.Visible = false;
					break;
				case "P":		//팝업으로 열때
					Top.Visible = false;
					menu_area.Attributes.Add("class", "nodisplay");
					ibtn_close.Visible = true;
					break;
			}
		}

		#endregion

		#region 버튼이벤트

		//메뉴구분 변경시
		protected void rbl_menu_div_SelectedIndexChanged(object sender, EventArgs e)
		{
			SearchProcess();
		}

		//검색
		protected void ibtn_search_Click(object sender, EventArgs e)
		{
			SearchProcess();
		}

		//저장
		protected void ibtn_save_Click(object sender, EventArgs e)
		{
			
			switch (rbl_menu_div.SelectedValue)
			{
				case "AF001":	//상위메뉴
					SetHighMenuViewOrder();
					break;
				case "AF002":	//하위메뉴
					SetMenuViewOrder();
					break;
			}
		}

		#region 상위메뉴
		//위로
		protected void lbtn_high_pgm_up_label_Click(object sender, EventArgs e)
		{
			UpHighPgm();
		}

		//아래로
		protected void lbtn_high_pgm_down_label_Click(object sender, EventArgs e)
		{
			DownHighPgm();
		}

		#endregion

		#region 하위메뉴
		//위로
		protected void lbtn_up_label_Click(object sender, EventArgs e)
		{
			//선택한 값이 디렉토리(D)이면 이동불가
			string [] ls_values = lbox_pgm_list.Items[lbox_pgm_list.SelectedIndex].Value.Split('|');
			string ls_pgm_div = "";	// D/F

			if (ls_values.Length > 1)
			{
				ls_pgm_div = ls_values[1];

				if (ls_pgm_div == "F")
				{
					//가장상위로 이동불가
					if (lbox_pgm_list.SelectedIndex == 1)
					{
						CallMsgBoxInAjax("MSG_ERR_179");	//하위메뉴는 최상위로 이동할 수 없습니다
					}
					else
					{
						UpPgm();
					}
				}
				else
				{
					CallMsgBoxInAjax("MSG_ERR_178");	//상위메뉴는 이동할 수 없습니다
				}
			}
		}

		//아래로
		protected void lbtn_down_label_Click(object sender, EventArgs e)
		{
			//선택한 값이 디렉토리(D)이면 이동불가
			string[] ls_values = lbox_pgm_list.Items[lbox_pgm_list.SelectedIndex].Value.Split('|');
			string ls_pgm_div = "";	// D/F

			if (ls_values.Length > 1)
			{
				ls_pgm_div = ls_values[1];

				if (ls_pgm_div == "F")
				{
					DownPgm();
				}
				else
				{
					CallMsgBoxInAjax("MSG_ERR_178");	//상위메뉴는 이동할 수 없습니다
				}
			}
		}

		#endregion

		#endregion

	}
}
